<!-- @format -->

<template>
  <Form :validation-schema="schema" v-slot="{ errors }" ref="formCom">
    <el-space direction="vertical" alignment="flex-start">
      <Field
        v-model="form.username"
        name="usernameFn"
        type="text"
        placeholder="请输入手机号"
      />
      <!-- 用户名校验失败提示 -->
      <div v-if="errors.usernameFn">{{ errors.usernameFn }}</div>
      <Field
        v-model="form.password"
        name="passwordFn"
        type="password"
        placeholder="请输密码"
      />
      <!-- 密码校验失败提示 -->
      <div v-if="errors.passwordFn">{{ errors.passwordFn }}</div>
      <button type="submit" @click="onSubmit">提交</button>
    </el-space>
  </Form>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { Form, Field } from 'vee-validate'

  // 定义表单数据
  const form = ref({
    username: null,
    password: null,
  })
  // 定义校验规则
  const schema = {
    usernameFn(value) {
      // 非空校验
      if (!value) return '用户名不能为空'
      // 字母开头,6-20字符之间
      if (!/^[a-zA-Z]\w{5,19}$/.test(value))
        return '必须以字母开头，且为6-20个字符'
      return true
    },
    passwordFn(value) {
      // 非空
      if (!value) return '密码不能为空'
      // 6-24个字符
      if (!/\w{6,24}/.test(value)) return '密码为6-24个字符'
      return true
    },
  }

  const formCom: any = ref(null)
  const onSubmit = (value: any) => {
    //整体校验
    formCom.value.validate().then((valid) => {
      if (valid) {
        console.log('校验通过')
      }
    })
  }
  onMounted(() => {
    formCom.value.resetForm()
  })
</script>
<style scoped></style>
